const { db, query } = require("../../db/db");
const util = require("util");
async function GetSettingTabs(req, res) {
  const select_menutabs_list_sql = util.format(
    "Select \
    MenuTabsId, \
    FMenuTabsId, \
    Type, \
   IFNULL(Icon,'') as Icon, \
   IFNULL(Path,'') as Path, \
   IFNULL(Name,'') as Name \
   From  MenuTabs where Type=%s",
    3
  );

  function buildMenuTree(menuList) {
    const menuMap = new Map();

    // 首先将所有菜单放入 Map 中，键为 MenuTabsId
    menuList.forEach((menu) => {
      menu.Children = []; // 初始化 Children 属性
      menuMap.set(menu.MenuTabsId, menu);
    });

    const tree = [];

    // 遍历菜单列表，构建树形结构
    menuList.forEach((menu) => {
      if (menu.FMenuTabsId === null || menu.FMenuTabsId === undefined) {
        // 如果没有父级菜单（即顶级菜单），则直接放入 tree 数组
        tree.push(menu);
      } else {
        // 否则将它添加到父级菜单的 Children 中
        const parentMenu = menuMap.get(menu.FMenuTabsId);
        if (parentMenu) {
          parentMenu.Children.push(menu);
        }
      }
    });

    return tree;
  }

  const select_menutabs_list_sql_res = await query(select_menutabs_list_sql);
  res.send({
    status: 0,
    tabList: buildMenuTree(select_menutabs_list_sql_res),
  });
}

module.exports = { GetSettingTabs };
